package org.example.adservice.service;

import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.example.adservice.config.MinioConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传服务
 */
@Slf4j
@Service
public class FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file) {
        try {
            log.info("开始上传文件: {}, 大小: {}, 类型: {}", 
                    file.getOriginalFilename(), file.getSize(), file.getContentType());
            log.info("MinIO配置 - endpoint: {}, bucket: {}, accessKey: {}", 
                    minioConfig.getEndpoint(), minioConfig.getBucketName(), minioConfig.getAccessKey());
            
            // 验证MinIO连接
            try {
                minioClient.listBuckets();
                log.info("MinIO连接测试成功");
            } catch (Exception e) {
                log.error("MinIO连接失败", e);
                throw new RuntimeException("MinIO服务连接失败，请检查配置");
            }
            
            // 检查存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(
                    BucketExistsArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .build()
            );
            log.info("存储桶 {} 是否存在: {}", minioConfig.getBucketName(), bucketExists);

            if (!bucketExists) {
                // 创建存储桶
                minioClient.makeBucket(
                        MakeBucketArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .build()
                );
                log.info("创建存储桶: {}", minioConfig.getBucketName());
                
                // 设置存储桶为公开读取
                String policy = "{\n" +
                        "  \"Version\": \"2012-10-17\",\n" +
                        "  \"Statement\": [\n" +
                        "    {\n" +
                        "      \"Effect\": \"Allow\",\n" +
                        "      \"Principal\": \"*\",\n" +
                        "      \"Action\": \"s3:GetObject\",\n" +
                        "      \"Resource\": \"arn:aws:s3:::" + minioConfig.getBucketName() + "/*\"\n" +
                        "    }\n" +
                        "  ]\n" +
                        "}";
                
                minioClient.setBucketPolicy(
                        SetBucketPolicyArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .config(policy)
                                .build()
                );
                log.info("设置存储桶 {} 为公开读取", minioConfig.getBucketName());
            }

            // 生成文件名
            String fileName = generateFileName(file.getOriginalFilename());
            log.info("生成的文件名: {}", fileName);

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );

            // 返回文件访问URL - 使用MinIO的标准文件访问路径
            // MinIO文件访问应该通过API端点，格式为: endpoint/bucket-name/object-name
            String fileUrl = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + fileName;
            log.info("文件上传成功: {}", fileUrl);
            return fileUrl;

        } catch (Exception e) {
            log.error("文件上传失败 - 详细错误信息", e);
            if (e instanceof MinioException) {
                MinioException me = (MinioException) e;
                log.error("MinIO错误代码: {}, 错误消息: {}", me.getClass().getSimpleName(), me.getMessage());
            }
            
            // 提供更友好的错误信息
            String errorMessage = e.getMessage();
            if (errorMessage.contains("Couldn't parse the specified URI")) {
                errorMessage = "MinIO服务地址配置错误，请检查endpoint配置";
            } else if (errorMessage.contains("Connection refused")) {
                errorMessage = "无法连接到MinIO服务，请确保MinIO服务正在运行";
            } else if (errorMessage.contains("Access Denied")) {
                errorMessage = "MinIO访问权限不足，请检查access-key和secret-key";
            }
            
            throw new RuntimeException("文件上传失败: " + errorMessage);
        }
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名
     * @return 删除是否成功
     */
    public boolean deleteFile(String fileName) {
        try {
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .object(fileName)
                            .build()
            );
            log.info("文件删除成功: {}", fileName);
            return true;
        } catch (Exception e) {
            log.error("文件删除失败", e);
            return false;
        }
    }

    /**
     * 生成文件名
     *
     * @param originalFilename 原始文件名
     * @return 新文件名
     */
    private String generateFileName(String originalFilename) {
        // 获取文件扩展名
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 生成日期路径
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = sdf.format(new Date());

        // 生成UUID文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");

        return datePath + "/" + uuid + extension;
    }

    /**
     * 从URL中提取文件名
     *
     * @param fileUrl 文件URL
     * @return 文件名
     */
    public String extractFileNameFromUrl(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return null;
        }
        
        String prefix = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/";
        if (fileUrl.startsWith(prefix)) {
            return fileUrl.substring(prefix.length());
        }
        
        return null;
    }
}